from celery import shared_task
import logging
from django.utils import timezone
from django.db.models import Count, Q
from django.db import transaction
from .models import Host, PasswordHistory, City, Datacenter, HostStatistics
from .utils import generate_password, change_linux_password

logger = logging.getLogger(__name__)


@shared_task
def rotate_host_password(host_id):
    """
    更新单个主机的密码
    """
    try:
        host = Host.objects.get(id=host_id)

        # 生成新密码
        new_password = generate_password()

        # 尝试在远程主机上修改密码
        if change_linux_password(host, new_password):
            # 密码修改成功，保存记录
            with transaction.atomic():
                # 记录旧密码
                PasswordHistory.objects.create(
                    host=host,
                    old_password=host.root_password,
                    new_password=new_password,
                    changed_by='system'
                )

                # 更新主机记录中的密码
                old_password = host.root_password
                host.root_password = new_password
                host.save()

                logger.info(f"主机 {host.hostname} 密码已成功更新")
            return True
        else:
            logger.error(f"无法更新主机 {host.hostname} 的密码")
            return False
    except Host.DoesNotExist:
        logger.error(f"找不到ID为 {host_id} 的主机")
        return False
    except Exception as e:
        logger.error(f"更新主机密码时出错: {str(e)}")
        return False


@shared_task
def rotate_all_hosts_passwords():
    """
    更新所有主机的密码
    """
    hosts = Host.objects.filter(is_active=True)

    for host in hosts:
        rotate_host_password.delay(host.id)

    return f"已触发 {hosts.count()} 台主机的密码轮换任务"


@shared_task
def generate_daily_statistics():
    """
    生成每日主机统计数据
    按城市和机房统计主机数量
    """
    today = timezone.now().date()

    # 获取所有数据中心
    datacenters = Datacenter.objects.all()

    for datacenter in datacenters:
        # 获取该数据中心的主机统计
        hosts = Host.objects.filter(datacenter=datacenter)
        host_count = hosts.count()
        online_count = hosts.filter(status='online').count()
        offline_count = hosts.filter(status='offline').count()
        maintenance_count = hosts.filter(status='maintenance').count()

        # 创建或更新统计记录
        HostStatistics.objects.update_or_create(
            date=today,
            city=datacenter.city,
            datacenter=datacenter,
            defaults={
                'host_count': host_count,
                'online_count': online_count,
                'offline_count': offline_count,
                'maintenance_count': maintenance_count
            }
        )

    return f"已为 {datacenters.count()} 个数据中心生成统计数据"